﻿//#define AutoMiniDebug
//创建时间: 2010-10-27
//创建作者: 李 城
//功能说明: 模板函数处理       
//最后修改: 2010-10-27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.IO;

using TRPOP.CMS.Model;
using TRPOP.Common;

namespace TRPOP.CMS.Plugin
{
    public class TemplateFunc : IFunc
    {

        /// <summary>
        /// date ( 格式字串, 时间戳)
        /// </summary>
        /// <param name="strFormat"></param>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public string date(string strFormat, DateTime datetime)
        {
            StringBuilder strbuild = new StringBuilder();
            strbuild.Append(
                           datetime.ToString(
                               strFormat.Replace("Y-m-d", "yyyy-MM-dd")
                                        .Replace("y-m-d", "yyyy-MM-dd")
                                        .Replace("Y/m/d", "yyyy/MM/dd")
                                        .Replace("y/m/d", "yyyy/MM/dd")
                                        .Replace("H:i:s", "HH:mm:ss")
                                        .Replace("m-d", "MM-dd")
                                        .Replace("m/d", "MM/dd")
                                        .Replace(" H:i", " HH:mm")
                                    )
                             );
            strbuild.Replace("Y", datetime.Year.ToString());
            strbuild.Replace("m", datetime.Month.ToString());
            strbuild.Replace("d", datetime.Day.ToString());
            strbuild.Replace("h", datetime.Hour.ToString());
            strbuild.Replace("i", datetime.Minute.ToString());
            strbuild.Replace("s", datetime.Second.ToString());
            return strbuild.ToString();
        }

        /// <summary>
        /// 中文字符串截取函数，根据开始位置和截取长度，自动截取字符串的长度，如果字符串长度小于截取长度，则返回原字符串，否则返回截取字符串+后缀，默认后缀为“...”
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intIndex"></param>
        /// <param name="intLength"></param>
        /// <returns></returns>
        public string CsubStr(string strContent, int intIndex, int intLength)
        {
            //return Yorkg_Base.Common.StringHelper.CutString(strContent, intIndex, intLength);
            strContent = strContent.Trim();
            if (intIndex < strContent.Length && intIndex > 0)
                strContent = strContent.Substring(intIndex);
            return StringExtension.CutStringWithByte(strContent, intLength * 2);
        }

        /// <summary>
        /// 中文字符串截取函数，根据开始位置和截取长度，自动截取字符串的长度，如果字符串长度小于截取长度，则返回原字符串，否则返回截取字符串+后缀，默认后缀为“...”
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intIndex"></param>
        /// <param name="intLength"></param>
        /// <param name="append"></param>
        /// <returns></returns>
        public string CsubStr(string strContent, int intIndex, int intLength, string append)
        {
            //return CsubStr(strContent, intIndex, intLength) + (strContent.Substring(intIndex).Length > intLength ? append : "");
            if (intIndex < strContent.Length && intIndex >= 0)
                strContent = strContent.Substring(intIndex);
            return StringExtension.CutStringWithByte(strContent, intLength * 2, append);
        }

        /// <summary>
        /// (去掉HTML标记)中文字符串截取函数，根据开始位置和截取长度，自动截取字符串的长度，如果字符串长度小于截取长度，则返回原字符串，否则返回截取字符串+后缀，默认后缀为“...”
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intIndex"></param>
        /// <param name="intLength"></param>
        /// <returns></returns>
        public string CsubStr_tags(string strContent, int intIndex, int intLength)
        {
            strContent = strContent.RemoveHtml();
            strContent = strContent.Trim();
            if (intIndex < strContent.Length && intIndex > 0)
                strContent = strContent.Substring(intIndex);
            return StringExtension.CutStringWithByte(strContent, intLength * 2);
        }

        /// <summary>
        /// (去掉HTML标记) 中文字符串截取函数，根据开始位置和截取长度，自动截取字符串的长度，如果字符串长度小于截取长度，则返回原字符串，否则返回截取字符串+后缀，默认后缀为“...”
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intIndex"></param>
        /// <param name="intLength"></param>
        /// <param name="append"></param>
        /// <returns></returns>
        public string CsubStr_tags(string strContent, int intIndex, int intLength, string append)
        {
            strContent = strContent.RemoveHtml();
            if (intIndex < strContent.Length && intIndex >= 0)
                strContent = strContent.Substring(intIndex);
            return StringExtension.CutStringWithByte(strContent, intLength * 2, append);
        }



        /// <summary>
        /// 清空字符串中的回车换行符，常用于js输出
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public string strip(string strContent)
        {
            return strContent.RTrim();
        }

        /// <summary>
        /// 重复显示字符串N次(重复次数)
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intCount"></param>
        /// <returns></returns>
        public string str_repeat(string strContent, int intCount)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < intCount; i++)
            {
                sb.Append(strContent);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 查看是否为空
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public bool empty(string strContent)
        {
            return strContent.IsEmpty();
        }

        /// <summary>
        /// 返回数量
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int count(object obj)
        {
            if (obj is string)
                return obj.ToString().Length;
            if (obj is DataTable)
                return (obj as DataTable).Rows.Count;
            if (obj is DataRow)
                return (obj as DataRow).Table.Columns.Count;
            return 0;
        }

        /// <summary>
        /// 分页函数
        /// </summary>
        /// <param name="TotalPage"></param>
        /// <param name="CurrentPage"></param>
        /// <param name="URL"></param>
        /// <returns></returns>
        public string list_page(string TotalPage, string CurrentPage, string URL, string showPageIndexCount, PageInfo m_pageinfo)
        {
            if (TotalPage.ToInt() <= 1)
                return "";
            if (m_pageinfo.TemplateTypeOut == EnumList.TemplateType.RecPage || m_pageinfo.TemplateTypeOut == EnumList.TemplateType.SearchPage)
                m_pageinfo.ListPagePubCountOut = 0;
            //{page} {nodeid}
            string strDynamicListPage = m_pageinfo.listPageRegName.ToLower().Replace("{nodeid}", m_pageinfo.NodeIdOut.ToString());
            strDynamicListPage = strDynamicListPage.ToLower().Replace("{indexid}", m_pageinfo.ContentIdOut.ToString());
            if (m_pageinfo.TemplateTypeOut == EnumList.TemplateType.SearchPage)
            {
                strDynamicListPage += "?nodeid=" + m_pageinfo.NodeIdOut.ToString()
                                    + "&page={page}"
                                    + "&" + SYSConfig.SystemVar_SearchFormInputName + "=" + Microsoft.JScript.GlobalObject.escape(m_pageinfo.SearchPageKeys.ToString());
            }
            int intshowPageIndexCount = int.Parse(showPageIndexCount) == 0 ? 5 : int.Parse(showPageIndexCount);
            int intIndexPage = int.Parse(CurrentPage);
            int intPageCount = int.Parse(TotalPage);
            string strPagename = URL.Substring(0, URL.LastIndexOf("."));
            string strPageExtName = URL.Substring(URL.LastIndexOf("."));
            if (strPagename.Contains("_"))
                strPagename = strPagename.Remove(strPagename.LastIndexOf("_"));
            string strReturn = "";

            string strPre = "<b><a href='{0}' >{1}</a></b>";
            string strNext = "<b><a href='{0}' >{1}</a></b>";
            string strIndex = "<a href='{0}'>{1}</a>&nbsp;";
            bool blnPre = intIndexPage > 1;//上一页 是否显示
            bool blnNext = intIndexPage < intPageCount;//下一页 是否显示

            #region 分页导航 例如: 1 2 3 [4] 5
            int intStart = 0;//起始位置
            int intCurrentShowCount = intshowPageIndexCount;//当前显示的页面导航的数目
            if (intshowPageIndexCount >= intPageCount)//如果要求显示的数量大于页总数
            {
                intStart = 1;
                intCurrentShowCount = intPageCount;
            }
            else
            {
                intStart = intIndexPage - ((intIndexPage % intshowPageIndexCount) == 0 ? intshowPageIndexCount : (intIndexPage % intshowPageIndexCount)) + 1;
                intCurrentShowCount = (intStart - 1 + intshowPageIndexCount) > intPageCount ? intPageCount : (intStart - 1 + intshowPageIndexCount);
            }
            for (int i = intStart; i <= intCurrentShowCount; i++)
            {
                if (i == intIndexPage)
                    strReturn += string.Format("<b>[{0}]</b>&nbsp;", intIndexPage);
                else
                {
                    strReturn += string.Format(strIndex,
                                                 getPageName(strPagename, i, strPageExtName, m_pageinfo.ListPagePubCountOut, strDynamicListPage),
                                               i.ToString()
                                               );
                }
            }
            #endregion

            strPre = blnPre ? string.Format(strPre,
                                             getPageName(strPagename, intIndexPage - 1, strPageExtName, m_pageinfo.ListPagePubCountOut, strDynamicListPage),
                                            "上一页"
                                            )
                             : "";
            strNext = blnNext ? string.Format(strNext,
                                            getPageName(strPagename, intIndexPage + 1, strPageExtName, m_pageinfo.ListPagePubCountOut, strDynamicListPage),
                                              "下一页"
                                              )
                              : "";
            //string strFormat = "<div class=\"pageingClass\">&nbsp;&nbsp;{0}" + strReturn + "&nbsp;&nbsp;{1}</div>";
            string strFormat = "&nbsp;&nbsp;{0}" + strReturn + "&nbsp;&nbsp;{1}";
            strReturn = string.Format(strFormat,
                                       strPre,
                                       strNext
                                       );
            return strReturn;
        }

        public string list_page(string TotalPage, string CurrentPage, string URL, string showPageIndexCount, string strlistPageRegName, int intNodeId, int intContentId, string strSearchPageKeys, EnumList.TemplateType oTemplateType, int intStaticPageNum)
        {
            return string.Empty;
        }

        #region 分页辅助方法
        public static string getPageName(string strPagename, int intIndexPage, string strPageExtName, int MaxStatic, string strDynamicListPage)
        {
            if (intIndexPage <= MaxStatic)
            {
                return strPagename + GetPageNameNum(intIndexPage) + strPageExtName;
            }
            else
                return strDynamicListPage.ToLower().Replace("{page}", intIndexPage.ToString());
        }
        public static string GetPageNameNum(int intPageIndex)
        {
            return intPageIndex <= 1 ? "" : ("_" + (intPageIndex - 1).ToString());
        }
        #endregion

        /// <summary>
        /// 根据文件的相对地址得到文件的访问地址（以http开头的）
        /// </summary>
        /// <param name="strImgSource"></param>
        /// <returns></returns>
        public string GetHttpURLForLocalFile(string strSourceUrl)
        {
            return strSourceUrl;
        }

        /// <summary>
        /// 自动压缩图片
        /// </summary>
        /// <param name="strSourceUrl"></param>
        /// <param name="strWidthAndLength"></param>
        /// <returns></returns>
        public string automini(string strSourceUrl, string strWidthAndLength)
        {
            /*
             *
             * 原来的实现方式 lcheng 2011.07.07
             *
            string strCacheKey = string.Format(CacheKeys.Template_Automini,strSourceUrl,strWidthAndLength);
            if (mICache.IsExist(strCacheKey) == false)
            {
                //原来的处理方法
                //string strreturn = automini_base(strSourceUrl, strWidthAndLength);
                string strreturn = automini_advance(strSourceUrl, strWidthAndLength);
                mICache.Save(strCacheKey, strreturn, CacheKeys.TemplateAutominiTimeSecond);
                return strreturn;
            }
            return mICache.Read(strCacheKey) as string;
            */
            return CacheHelper.GetByICache<string>(
                    string.Format(CacheKeys.Template_Automini, strSourceUrl, strWidthAndLength),
                    CacheKeys.TemplateAutominiTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        return automini_advance(strSourceUrl, strWidthAndLength);
                    }
            );

        }

        /// <summary>
        /// 压缩图片的基本操作方法 （根据文件来源，在本地读取文件，而后进行压缩）
        /// </summary>
        /// <param name="strSourceUrl"></param>
        /// <param name="strWidthAndLength"></param>
        /// <returns></returns>
        public string automini_base(string strSourceUrl, string strWidthAndLength)
        {
            strSourceUrl = strSourceUrl.Trim().ToLower();
            strWidthAndLength = strWidthAndLength.Trim().ToLower();
            int intWidth = 0, intHeight = 0;
            string strOldPath = string.Empty, strNewPath = string.Empty;
            #region 数据验证
            //如果 源文件地址不存在 或 源文件地址不存在. 或 制定的宽高不含* 或 宽高字符串的格式不正确（100*100这种格式） 则说明函数设置有问题
            if (strSourceUrl.Length <= 0 || strSourceUrl.Contains(".") == false || strWidthAndLength.Contains("*") == false || strWidthAndLength.Split('*').Length != 2)
                return strSourceUrl
#if AutoMiniDebug
 + "automini函数设置不对"
#endif
;
            string strSatrtChar = strSourceUrl.Substring(0, 1);
            intWidth = strWidthAndLength.Split('*')[0].ToInt();
            intHeight = strWidthAndLength.Split('*')[1].ToInt();
            //如果 长宽的值不正常，则返回错误信息或源地址
            if (intWidth <= 0 || intHeight <= 0)
                return strSourceUrl
#if AutoMiniDebug
 + "automini函数长宽设置不对"
#endif
;
            #endregion
            switch (strSatrtChar)
            {
                case "/":
                    #region 从图片库里查找，并作处理
                    Match oMatchPhoto = new Regex(@"/(?<name>[^/]*)[.](?<extname>[\w]*)", RegexOptions.Multiline | RegexOptions.IgnoreCase).Match(strSourceUrl);
                    if (oMatchPhoto.Success == false)
                        return strSourceUrl
#if AutoMiniDebug
 + "以/开头的图片地址，找不到文件名和扩展名"
#endif
;
                    string strHttpURL = string.Empty;
                    string strPhotoPath = string.Empty;
                    string strNewPhoto = oMatchPhoto.Groups["name"].Value + "_" + strWidthAndLength.Replace("*", "×") + "." + oMatchPhoto.Groups["extname"].Value;
                    if (ITemplateAccess.GetIDalInstance().autoMiniGetPhotoInfo(strSourceUrl, ref strHttpURL, ref strPhotoPath) == false)
                        return strSourceUrl
#if AutoMiniDebug
 + "以/开头的图片地址，根据图片地址在图片库里找不到对应的图片"
#endif
;
                    strOldPath = Common.Util.GetMapPath(strSourceUrl);
                    strNewPath = Common.Util.GetMapPath(strPhotoPath + strNewPhoto);
                    if (System.IO.File.Exists(strNewPath))
                        return strHttpURL + strNewPhoto;
                    if (strOldPath.Contains(":\\") && System.IO.File.Exists(strOldPath))
                    {
                        using (System.IO.StreamReader strmReader = new System.IO.StreamReader(strOldPath))
                        {
                            /* 
                             *  原来的代码
                             * if (Yorkg_Base.Common.ImageHelper.ResizeImageAbsolute(strmReader.BaseStream, strNewPath, intWidth, intHeight))
                             */
                            if (TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                            {
                                return strHttpURL + strNewPhoto;
                            }
                        }
                    }
                    else
                    {
                        string strImgServerHttpURL = ITemplateAccess.GetIDalInstance().GetTemplateVar("ImgServerHttp");
                        if (String.IsNullOrEmpty(strImgServerHttpURL))
                            strImgServerHttpURL = "http://content.yorkbbs.ca";
                        using (System.IO.StreamReader strmReader = DownURLFile.ReadURLFile(strImgServerHttpURL + strSourceUrl))
                        {
                            if (strmReader != null)
                            {
                                /*
                                 * 之前的代码
                                 * if (Yorkg_Base.Common.ImageHelper.ResizeImageAbsolute(strmReader.BaseStream, strNewPath, intWidth, intHeight))
                                 * 
                                 */
                                if (TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                                {
                                    return strHttpURL + strNewPhoto;
                                }
                            }
                        }
                    }
                    return strSourceUrl;
                    #endregion
                case "h":
                    #region 原来的针对 http:// 这种信息的处理
                    // 直接检测 http:// 这样的图片是否存在，如果存在，则直接返回
                    string strNewHttpRetrun = autominiGetNewFile(strSourceUrl, strWidthAndLength.Replace("*", "×"));
                    if (autominiFileTest(strNewHttpRetrun))
                        return strNewHttpRetrun;
                    //
                    string strfileUrl = strSourceUrl;
                    string strHTTPURL = "";
                    string strNewDictionary = "";
                    Match oMatch = CommonRegex.MatchHttpUrl(strfileUrl);
                    if (oMatch.Success)
                    {
                        strfileUrl = oMatch.Groups["root"].ToString();
                        strHTTPURL = oMatch.Groups["url"].ToString();
                    }
                    TRPOP.CMS.Model.PSNInfo oPSNInfo = ITemplateAccess.GetIDalInstance().GetInfoByHttp(strHTTPURL);
                    if (oPSNInfo == null || oPSNInfo.Url.IsEmpty() || oPSNInfo.Url.ToLower().Contains(strHTTPURL) == false)
                        return strSourceUrl;
                    strfileUrl = strfileUrl.Replace(oPSNInfo.Url.ToLower().Trim(), "");
                    strfileUrl = strfileUrl.StartsWith("/") ? (oPSNInfo.Root + strfileUrl) : (oPSNInfo.Root + "/" + strfileUrl);
                    strOldPath = Common.Util.GetMapPath(strfileUrl);
                    if (System.IO.File.Exists(strOldPath) == false)
                        return strSourceUrl;
                    #region 创建 autoMini  文件夹
                    strNewDictionary = strfileUrl.Remove(strfileUrl.LastIndexOf("/")) + "/autoMini";
                    if (System.IO.Directory.Exists(Common.Util.GetMapPath(strNewDictionary)) == false)
                    {
                        System.IO.Directory.CreateDirectory(Common.Util.GetMapPath(strNewDictionary));
                    }
                    #endregion
                    string strNewFile =
                                        strfileUrl.Remove(strfileUrl.LastIndexOf("/")) + "/autoMini" +
                                        strfileUrl.Substring(strfileUrl.LastIndexOf("/"), strfileUrl.LastIndexOf(".") - strfileUrl.LastIndexOf("/")) +
                                        "_" +
                                        strWidthAndLength.Replace("*", "×") +
                                        strfileUrl.Substring(strfileUrl.LastIndexOf("."));

                    strNewPath = Common.Util.GetMapPath(strNewFile);
                    bool blnNewFileExist = false;
                    if (System.IO.File.Exists(strNewPath) == false)
                    {
                        System.IO.StreamReader strmReader = new System.IO.StreamReader(strOldPath);
                        /*
                         * 之前的代码
                         * if (Yorkg_Base.Common.ImageHelper.ResizeImageAbsolute(strmReader.BaseStream, strNewPath, intWidth, intHeight))
                         * 
                         */
                        if (TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                            blnNewFileExist = true;
                        strmReader.Dispose();
                        strmReader.Close();

                    }
                    else
                        blnNewFileExist = true;
                    if (blnNewFileExist)
                    {
                        int intIndex = strNewFile.Trim().ToLower().IndexOf(oPSNInfo.Root.Trim().ToLower());
                        if (intIndex == 0)
                            strNewFile = strNewFile.Trim().ToLower().Remove(0, oPSNInfo.Root.Trim().ToLower().Length);
                        return oPSNInfo.Url + (strNewFile.StartsWith("/") ? "" : "/") + strNewFile;
                    }
                    return strSourceUrl
#if AutoMiniDebug
 + "通过http类型的地址找不到图片地址" + strOldPath + "新地址是" + strNewPath;
#endif
;
                    #endregion
                default:
                    return strSourceUrl;
            }
        }

        /// <summary>
        /// 压缩图片的基本操作方法 （根据文件来源，在本地读取文件(如果本地文件不存在，则进一步通过http读取)，而后进行压缩）
        /// </summary>
        /// <param name="strSourceUrl"></param>
        /// <param name="strWidthAndLength"></param>
        /// <returns></returns>
        public string automini_advance(string strSourceUrl, string strWidthAndLength)
        {
            strSourceUrl = strSourceUrl.Trim().ToLower();
            strWidthAndLength = strWidthAndLength.Trim().ToLower();
            int intWidth = 0, intHeight = 0;
            string strOldPath = string.Empty, strNewPath = string.Empty;
            #region 数据验证
            //如果 源文件地址不存在 或 源文件地址不存在. 或 制定的宽高不含* 或 宽高字符串的格式不正确（100*100这种格式） 则说明函数设置有问题
            if (strSourceUrl.Length <= 0 || strSourceUrl.Contains(".") == false || strWidthAndLength.Contains("*") == false || strWidthAndLength.Split('*').Length != 2)
                return strSourceUrl
#if AutoMiniDebug
 + "automini函数设置不对"
#endif
;
            string strSatrtChar = strSourceUrl.Substring(0, 1);
            intWidth = strWidthAndLength.Split('*')[0].ToInt();
            intHeight = strWidthAndLength.Split('*')[1].ToInt();
            //如果 长宽的值不正常，则返回错误信息或源地址
            if (intWidth <= 0 || intHeight <= 0)
                return strSourceUrl
#if AutoMiniDebug
 + "automini函数长宽设置不对"
#endif
;
            #endregion
            switch (strSatrtChar)
            {
                case "/":
                    #region 从图片库里查找，并作处理
                    Match oMatchPhoto = new Regex(@"/(?<name>[^/]*)[.](?<extname>[\w]*)", RegexOptions.Multiline | RegexOptions.IgnoreCase).Match(strSourceUrl);
                    if (oMatchPhoto.Success == false)
                        return strSourceUrl
#if AutoMiniDebug
 + "以/开头的图片地址，找不到文件名和扩展名"
#endif
;
                    string strHttpURL = string.Empty;
                    string strPhotoPath = string.Empty;
                    string strNewPhoto = oMatchPhoto.Groups["name"].Value + "_" + strWidthAndLength.Replace("*", "×") + "." + oMatchPhoto.Groups["extname"].Value;
                    if (ITemplateAccess.GetIDalInstance().autoMiniGetPhotoInfo(strSourceUrl, ref strHttpURL, ref strPhotoPath) == false)
                        return strSourceUrl
#if AutoMiniDebug
 + "以/开头的图片地址，根据图片地址在图片库里找不到对应的图片"
#endif
;
                    strOldPath = Common.Util.GetMapPath(strSourceUrl);
                    strNewPath = Common.Util.GetMapPath(strPhotoPath + strNewPhoto);
                    if (System.IO.File.Exists(strNewPath))
                        return strHttpURL + strNewPhoto;
                    if (strOldPath.Contains(":\\") && System.IO.File.Exists(strOldPath))
                    {
                        using (System.IO.StreamReader strmReader = new System.IO.StreamReader(strOldPath))
                        {
                            /* 
                             *  原来的代码
                             * if (Yorkg_Base.Common.ImageHelper.ResizeImageAbsolute(strmReader.BaseStream, strNewPath, intWidth, intHeight))
                             */
                            if (TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                            {
                                return strHttpURL + strNewPhoto;
                            }
                        }
                    }
                    else
                    {
                        string strImgServerHttpURL = ITemplateAccess.GetIDalInstance().GetTemplateVar("ImgServerHttp");
                        if (String.IsNullOrEmpty(strImgServerHttpURL))
                            strImgServerHttpURL = "http://content.yorkbbs.ca";
                        using (System.IO.StreamReader strmReader = DownURLFile.ReadURLFile(strImgServerHttpURL + strSourceUrl))
                        {
                            if (strmReader != null)
                            {
                                /*
                                 * 之前的代码
                                 * if (Yorkg_Base.Common.ImageHelper.ResizeImageAbsolute(strmReader.BaseStream, strNewPath, intWidth, intHeight))
                                 * 
                                 */
                                if (TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                                {
                                    return strHttpURL + strNewPhoto;
                                }
                            }
                        }
                    }
                    return strSourceUrl;
                    #endregion
                case "h":
                    #region http:// 这种信息的处理
                    // 直接检测 http:// 这样的图片是否存在，如果存在，则直接返回
                    string strNewHttpRetrun = autominiGetNewFile(strSourceUrl, strWidthAndLength.Replace("*", "×"));
                    if (autominiFileTest(strNewHttpRetrun))
                        return strNewHttpRetrun;
                    //
                    string strfileUrl = strSourceUrl;
                    string strHTTPURL = "";
                    string strNewDictionary = "";
                    Match oMatch = CommonRegex.MatchHttpUrl(strfileUrl);
                    if (oMatch.Success)
                    {
                        strfileUrl = oMatch.Groups["root"].ToString();
                        strHTTPURL = oMatch.Groups["url"].ToString();
                    }
                    TRPOP.CMS.Model.PSNInfo oPSNInfo = ITemplateAccess.GetIDalInstance().GetInfoByHttp(strHTTPURL);
                    if (oPSNInfo == null || oPSNInfo.Url.IsEmpty() || oPSNInfo.Url.ToLower().Contains(strHTTPURL) == false)
                        return strSourceUrl;
                    strfileUrl = strfileUrl.Replace(oPSNInfo.Url.ToLower().Trim(), "");
                    strfileUrl = strfileUrl.StartsWith("/") ? (oPSNInfo.Root + strfileUrl) : (oPSNInfo.Root + "/" + strfileUrl);
                    strOldPath = Common.Util.GetMapPath(strfileUrl);
                    if (System.IO.File.Exists(strOldPath) == false)
                    {
                        return autominiHttpToLocal(strSourceUrl, intWidth, intHeight);
                    }
                    #region 创建 autoMini  文件夹
                    strNewDictionary = strfileUrl.Remove(strfileUrl.LastIndexOf("/")) + "/autoMini";
                    if (System.IO.Directory.Exists(Common.Util.GetMapPath(strNewDictionary)) == false)
                    {
                        System.IO.Directory.CreateDirectory(Common.Util.GetMapPath(strNewDictionary));
                    }
                    #endregion
                    string strNewFile =
                                        strfileUrl.Remove(strfileUrl.LastIndexOf("/")) + "/autoMini" +
                                        strfileUrl.Substring(strfileUrl.LastIndexOf("/"), strfileUrl.LastIndexOf(".") - strfileUrl.LastIndexOf("/")) +
                                        "_" +
                                        strWidthAndLength.Replace("*", "×") +
                                        strfileUrl.Substring(strfileUrl.LastIndexOf("."));

                    strNewPath = Common.Util.GetMapPath(strNewFile);
                    bool blnNewFileExist = false;
                    if (System.IO.File.Exists(strNewPath) == false)
                    {
                        System.IO.StreamReader strmReader = new System.IO.StreamReader(strOldPath);
                        /*
                         * 之前的代码
                         * if (Yorkg_Base.Common.ImageHelper.ResizeImageAbsolute(strmReader.BaseStream, strNewPath, intWidth, intHeight))
                         * 
                         */
                        if (TRPOP.Common.ImageTools.ResizeImage(strmReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                            blnNewFileExist = true;
                        strmReader.Dispose();
                        strmReader.Close();

                    }
                    else
                        blnNewFileExist = true;
                    if (blnNewFileExist)
                    {
                        int intIndex = strNewFile.Trim().ToLower().IndexOf(oPSNInfo.Root.Trim().ToLower());
                        if (intIndex == 0)
                            strNewFile = strNewFile.Trim().ToLower().Remove(0, oPSNInfo.Root.Trim().ToLower().Length);
                        return oPSNInfo.Url + (strNewFile.StartsWith("/") ? "" : "/") + strNewFile;
                    }
                    return strSourceUrl
#if AutoMiniDebug
 + "通过http类型的地址找不到图片地址" + strOldPath + "新地址是" + strNewPath;
#endif
;
                    #endregion
                default:
                    return strSourceUrl;
            }
        }

        /// <summary>
        /// 将HTTP类型的图片压缩至本地
        /// </summary>
        /// <param name="strSourceUrl">http类型的图片地址</param>
        /// <param name="intWidth">压缩后的长度</param>
        /// <param name="intHeight">压缩后的宽度</param>
        /// <returns></returns>
        public string autominiHttpToLocal(string strSourceUrl, int intWidth, int intHeight)
        {
            //读取http图片，如果失败，则直接返回原地址
            StreamReader oStreamReader = DownURLFile.ReadURLFile(strSourceUrl);
            if (oStreamReader == null)
                return strSourceUrl;
            //如果 长宽的值不正常，则返回源地址
            if (intWidth <= 0 || intHeight <= 0)
                return strSourceUrl;

            //原来的http地址的图片在本地的目录
            string strOldPath = string.Empty;
            //新的压缩过的图片存放的目录
            string strNewPath = string.Empty;
            //原来的文件目录
            string strSourcefileRoot = string.Empty;
            //原来的Http域名
            string strSourceHTTPURL = string.Empty;
            //压缩后的文件存放的目录
            string strNewDictionary = string.Empty;

            //根据正则，将http域名和目录分离开来 如果匹配不成功，则返回原来的地址
            Match oMatch = CommonRegex.MatchHttpUrl(strSourceUrl);
            if (oMatch.Success == false)
            {
                return strSourceUrl;
            }
            strSourcefileRoot = oMatch.Groups["root"].ToString();
            strSourceHTTPURL = oMatch.Groups["url"].ToString();

            //获取第一个与http域名相符的PSNinfo，以此PSN作为依据,找到源文件真正的在服务器的地址
            TRPOP.CMS.Model.PSNInfo oPSNInfo = ITemplateAccess.GetIDalInstance().GetInfoByHttp(strSourceHTTPURL);
            if (oPSNInfo == null || oPSNInfo.Url.IsEmpty() || oPSNInfo.Url.ToLower().Contains(strSourceHTTPURL) == false)
                return strSourceUrl;
            //strSourcefileRoot = strSourcefileRoot.Replace(oPSNInfo.Url.ToLower().Trim(), "");
            strSourcefileRoot = strSourcefileRoot.StartsWith("/") ? (oPSNInfo.Root + strSourcefileRoot) : (oPSNInfo.Root + "/" + strSourcefileRoot);
            strOldPath = Common.Util.GetMapPath(strSourcefileRoot);

            //创建 autoMini  文件夹
            strNewDictionary = strSourcefileRoot.Remove(strSourcefileRoot.LastIndexOf("/")) + "/autoMini";
            if (System.IO.Directory.Exists(Common.Util.GetMapPath(strNewDictionary)) == false)
            {
                System.IO.Directory.CreateDirectory(Common.Util.GetMapPath(strNewDictionary));
            }

            //组合定义压缩的文件的名字（带目录）
            string strNewFile =
                                strNewDictionary +
                                strSourcefileRoot.Substring(strSourcefileRoot.LastIndexOf("/"), strSourcefileRoot.LastIndexOf(".") - strSourcefileRoot.LastIndexOf("/")) +
                                "_" +
                                intWidth + "×" + intHeight +
                                strSourcefileRoot.Substring(strSourcefileRoot.LastIndexOf("."));
            strNewPath = Common.Util.GetMapPath(strNewFile);
            //压缩文件： 如果压缩文件已存在，则直接返回压缩文件，反之则进行压缩后，返回地址
            bool blnNewFileExist = false;
            if (System.IO.File.Exists(strNewPath) == false)
            {
                if (TRPOP.Common.ImageTools.ResizeImage(oStreamReader.BaseStream, strNewPath, intWidth, intHeight, SYSConfig.Attachment_blnPreserverAspectRatio, 80))
                    blnNewFileExist = true;
                oStreamReader.Dispose();
                oStreamReader.Close();
            }
            else
                blnNewFileExist = true;
            if (blnNewFileExist)
            {
                int intIndex = strNewFile.Trim().ToLower().IndexOf(oPSNInfo.Root.Trim().ToLower());
                if (intIndex == 0)
                    strNewFile = strNewFile.Trim().ToLower().Remove(0, oPSNInfo.Root.Trim().ToLower().Length);
                return oPSNInfo.Url + (strNewFile.StartsWith("/") ? "" : "/") + strNewFile;
            }
            return strSourceUrl;
        }

        /// <summary>
        /// 获取： 如果成功压缩，那么需要返回的地址
        /// </summary>
        /// <param name="strSource"></param>
        /// <param name="extraName"></param>
        /// <returns></returns>
        private string autominiGetNewFile(string strSource, string extraName)
        {
            if (strSource.Contains(".") == false)
                return string.Empty;
            return strSource.Substring(0, strSource.LastIndexOf(".")) + extraName + strSource.Substring(strSource.LastIndexOf("."));
        }

        /// <summary>
        /// 检测以压缩的文件是否存在
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        private bool autominiFileTest(string strSource)
        {
            StreamReader oStreamReader;
            if ((oStreamReader = DownURLFile.ReadURLFile(strSource)) == null)
                return false;
            else
            {
                oStreamReader.Dispose();
                return true;
            }
        }

        /// <summary>
        /// 去除html标签，并返回指定的长度的字符串
        /// </summary>
        /// <param name="strHTML"></param>
        /// <param name="length">如果为0 则返回所有</param>
        /// <returns></returns>
        public string removeHTML(string strHTML, string length)
        {
            string strReturn = strHTML.RemoveHtml();
            int intlength = 0;
            int.TryParse(length, out intlength);
            if (intlength <= 0)
                return strReturn;
            else
                return StringExtension.CutString(strReturn, 0, intlength);
        }

        /// <summary>
        /// 搜索关键字
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="strSplit"></param>
        /// <param name="strURL"></param>
        /// <returns></returns>
        public string searchSplit(string keys, string strURL)
        {
            StringBuilder strBuilder = new StringBuilder();
            foreach (string strTemp in keys.Split(','))
            {
                if (strTemp.IsEmpty() == false)
                {
                    strBuilder.Append(string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>&nbsp;&nbsp;&nbsp;&nbsp;",
                                                    string.Format(strURL, Microsoft.JScript.GlobalObject.escape(strTemp)),
                                                    strTemp)
                                      );
                }
            }
            return strBuilder.ToString();
        }

        /// <summary>
        /// 搜索关键字
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="strURL"></param>
        /// <param name="strPre"></param>
        /// <param name="strEnd"></param>
        /// <returns></returns>
        public string searchSplit(string keys, string strURL, string strPre, string strEnd)
        {
            StringBuilder strBuilder = new StringBuilder();
            foreach (string strTemp in keys.Split(','))
            {
                if (strTemp.IsEmpty() == false)
                {
                    strBuilder.Append(strPre
                                     + string.Format("<a href=\"{0}\" target=\"_blank\"  title=\"{1}\" >{1}</a>&nbsp;&nbsp;&nbsp;&nbsp;",
                                                    string.Format(strURL, Microsoft.JScript.GlobalObject.escape(strTemp)),
                                                    strTemp)
                                                    + strEnd
                                      );
                }
            }
            return strBuilder.ToString();
        }
        /// <summary>
        /// 搜索关键字
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="strURL"></param>
        /// <param name="strPre"></param>
        /// <param name="strEnd"></param>
        /// <param name="strAparam"></param>
        /// <returns></returns>
        public string searchSplit(string keys, string strURL, string strPre, string strEnd, string strAparam)
        {
            StringBuilder strBuilder = new StringBuilder();
            foreach (string strTemp in keys.Split(','))
            {
                if (strTemp.IsEmpty() == false)
                {
                    strBuilder.Append(strPre
                                     + string.Format("<a href=\"{0}\" target=\"_blank\"  title=\"{1}\" {2} >{1}</a>&nbsp;&nbsp;&nbsp;&nbsp;",
                                                    string.Format(strURL, Microsoft.JScript.GlobalObject.escape(strTemp)),
                                                    strTemp,
                                                    strAparam
                                                    )
                                                    + strEnd
                                      );
                }
            }
            return strBuilder.ToString();
        }
        /// <summary>
        /// 搜索关键字
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="strURL"></param>
        /// <param name="strPre"></param>
        /// <param name="strEnd"></param>
        /// <param name="strAparam"></param>
        /// <param name="intCount"></param>
        /// <returns></returns>
        public string searchSplit(string keys, string strURL, string strPre, string strEnd, string strAparam,int intCount)
        {
            int intIndex = 0;

            StringBuilder strBuilder = new StringBuilder();

            foreach (string strTemp in keys.Split(','))
            {
                if (strTemp.IsEmpty() == false)
                {
                    intIndex++;
                    strBuilder.Append(strPre
                                     + string.Format("<a href=\"{0}\" target=\"_blank\"  title=\"{1}\" {2} >{1}</a>&nbsp;&nbsp;&nbsp;&nbsp;",
                                                    string.Format(strURL, Microsoft.JScript.GlobalObject.escape(strTemp)),
                                                    strTemp,
                                                    strAparam
                                                    )
                                                    + strEnd
                                      );
                }
                if (intIndex > intCount)
                    break;
            }
            return strBuilder.ToString();
        }

        /// <summary>
        /// (HTML智能截取)中文字符串截取函数，根据开始位置和截取长度，自动截取字符串的长度，如果字符串长度小于截取长度，则返回原字符串，否则返回截取字符串+后缀，默认后缀为“...”
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intIndex"></param>
        /// <param name="intLength"></param>
        /// <returns></returns>
        public string CsubStrForHtml(string strContent, int intIndex, int intLength)
        {
            return TRPOP.Common.CutHtml.subStringHTML(strContent, intLength, "");
        }

        /// <summary>
        /// (HTML智能截取)中文字符串截取函数，根据开始位置和截取长度，自动截取字符串的长度，如果字符串长度小于截取长度，则返回原字符串，否则返回截取字符串+后缀，默认后缀为“...”
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="intIndex"></param>
        /// <param name="intLength"></param>
        /// <param name="strAppend"></param>
        /// <returns></returns>
        public string CsubStrForHtml(string strContent, int intIndex, int intLength, string strAppend)
        {
            return TRPOP.Common.CutHtml.subStringHTML(strContent, intLength, strAppend);
        }

    }
}
